package com.duoec.magichour.controller.api;

import com.duoec.magichour.core.annotation.Access;
import com.duoec.magichour.core.web.BaseApiController;
import com.duoec.magichour.dto.BaseResponse;
import com.duoec.magichour.dto.request.ArticleCateSave;
import com.duoec.magichour.enums.RoleEnum;
import com.duoec.magichour.service.ArticleCateService;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 文章分类接口
 */
@RestController
@RequestMapping("/api/article-cate")
public class ArticleCateApiController extends BaseApiController {
    @Autowired
    private ArticleCateService articleCateService;

    /**
     * 编辑分类
     *
     * @param request 文章分类信息
     * @return 新增或修改的文章分类ID
     */
    @RequestMapping(method = RequestMethod.POST)
    public BaseResponse<Integer> save(@RequestBody ArticleCateSave request) {
        //检查参数
        String name = request.getName();
        if (Strings.isNullOrEmpty(name) || name.length() < 2) {
            return BaseResponse.error(BaseResponse.CODE_PARAM_INVALID, "分类名称长度必须大于1！");
        }
        Integer parentId = request.getParentId();
        if (parentId != null) {
            //检查是否合法的父级ID，如果不合法，会抛个异常
            articleCateService.availableParentId(request.getId(), parentId);
        }
        //检查当前ID是否合法
        Integer id = request.getId();
        if (id != null) {
            if (!articleCateService.exists(id)) {
                return BaseResponse.error(BaseResponse.CODE_PARAM_INVALID, "分类不存在！");
            }
        }
        id = articleCateService.save(getUserInfo(), request);
        return BaseResponse.success(id);
    }

    /**
     * 删除文章分类
     *
     * @param id 文章ID
     * @return
     */
    @Access(RoleEnum.ADMIN)
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:\\d+}")
    public BaseResponse<Integer> delete(
            @PathVariable int id
    ) {
        if (!articleCateService.exists(id)) {
            return BaseResponse.error(BaseResponse.CODE_PARAM_INVALID, "分类不存在！");
        }
        articleCateService.delete(id);
        return BaseResponse.success(id);
    }
}
